#!/bin/sh
#
# SAPDatabase
#
# Description:	Manages any type of SAP supported database instance
#               as a High-Availability OCF compliant resource.
#
# Author:       Alexander Krauth, October 2006
# Support:      linux@sap.com
# License:      GNU General Public License (GPL)
# Copyright:    (c) 2006, 2007, 2010, 2012 Alexander Krauth
#
# An example usage:
#      See usage() function below for more details...
#
# OCF instance parameters:
#       OCF_RESKEY_SID
#       OCF_RESKEY_DIR_EXECUTABLE      (optional, well known directories will be searched by default)
#       OCF_RESKEY_DBTYPE              (mandatory, one of the following values: ORA,ADA,DB6,SYB,HDB)
#       OCF_RESKEY_DBINSTANCE          (optional, Database instance name, if not equal to SID)
#       OCF_RESKEY_DBOSUSER            (optional, the Linux user that owns the database processes on operating system level)
#       OCF_RESKEY_STRICT_MONITORING   (optional, activate application level monitoring - with Oracle a failover will occur in case of an archiver stuck)
#       OCF_RESKEY_AUTOMATIC_RECOVER   (optional, automatic startup recovery, default is false)
#       OCF_RESKEY_MONITOR_SERVICES    (optional, default is to monitor all database services)
#       OCF_RESKEY_PRE_START_USEREXIT  (optional, lists a script which can be executed before the resource is started)
#       OCF_RESKEY_POST_START_USEREXIT (optional, lists a script which can be executed after the resource is started)
#       OCF_RESKEY_PRE_STOP_USEREXIT   (optional, lists a script which can be executed before the resource is stopped)
#       OCF_RESKEY_POST_STOP_USEREXIT  (optional, lists a script which can be executed after the resource is stopped)
#     Deprecated parameters:
#       OCF_RESKEY_NETSERVICENAME
#       OCF_RESKEY_DBJ2EE_ONLY
#       OCF_RESKEY_JAVA_HOME
#       OCF_RESKEY_DIR_BOOTSTRAP
#       OCF_RESKEY_DIR_SECSTORE
#       OCF_RESKEY_DB_JARS
#
#######################################################################
# Initialization:

: ${OCF_FUNCTIONS_DIR=${OCF_ROOT}/lib/heartbeat}
. ${OCF_FUNCTIONS_DIR}/ocf-shellfuncs

# Parameter defaults

OCF_RESKEY_SID_default=""
OCF_RESKEY_DIR_EXECUTABLE_default="/usr/sap/hostctrl/exe"
OCF_RESKEY_DBTYPE_default=""
OCF_RESKEY_DBINSTANCE_default=""
OCF_RESKEY_DBOSUSER_default=""
OCF_RESKEY_NETSERVICENAME_default=""
OCF_RESKEY_DBJ2EE_ONLY_default=""
OCF_RESKEY_JAVA_HOME_default=""
OCF_RESKEY_STRICT_MONITORING_default="false"
OCF_RESKEY_AUTOMATIC_RECOVER_default="false"
OCF_RESKEY_MONITOR_SERVICES_default=""
OCF_RESKEY_DIR_BOOTSTRAP_default=""
OCF_RESKEY_DIR_SECSTORE_default=""
OCF_RESKEY_DB_JARS_default=""
OCF_RESKEY_PRE_START_USEREXIT_default=""
OCF_RESKEY_POST_START_USEREXIT_default=""
OCF_RESKEY_PRE_STOP_USEREXIT_default=""
OCF_RESKEY_POST_STOP_USEREXIT_default=""

: ${OCF_RESKEY_SID=${OCF_RESKEY_SID_default}}
: ${OCF_RESKEY_DIR_EXECUTABLE=${OCF_RESKEY_DIR_EXECUTABLE_default}}
: ${OCF_RESKEY_DBTYPE=${OCF_RESKEY_DBTYPE_default}}
: ${OCF_RESKEY_DBINSTANCE=${OCF_RESKEY_DBINSTANCE_default}}
: ${OCF_RESKEY_DBOSUSER=${OCF_RESKEY_DBOSUSER_default}}
: ${OCF_RESKEY_NETSERVICENAME=${OCF_RESKEY_NETSERVICENAME_default}}
: ${OCF_RESKEY_DBJ2EE_ONLY=${OCF_RESKEY_DBJ2EE_ONLY_default}}
: ${OCF_RESKEY_JAVA_HOME=${OCF_RESKEY_JAVA_HOME_default}}
: ${OCF_RESKEY_STRICT_MONITORING=${OCF_RESKEY_STRICT_MONITORING_default}}
: ${OCF_RESKEY_AUTOMATIC_RECOVER=${OCF_RESKEY_AUTOMATIC_RECOVER_default}}
: ${OCF_RESKEY_MONITOR_SERVICES=${OCF_RESKEY_MONITOR_SERVICES_default}}
: ${OCF_RESKEY_DIR_BOOTSTRAP=${OCF_RESKEY_DIR_BOOTSTRAP_default}}
: ${OCF_RESKEY_DIR_SECSTORE=${OCF_RESKEY_DIR_SECSTORE_default}}
: ${OCF_RESKEY_DB_JARS=${OCF_RESKEY_DB_JARS_default}}
: ${OCF_RESKEY_PRE_START_USEREXIT=${OCF_RESKEY_PRE_START_USEREXIT_default}}
: ${OCF_RESKEY_POST_START_USEREXIT=${OCF_RESKEY_POST_START_USEREXIT_default}}
: ${OCF_RESKEY_PRE_STOP_USEREXIT=${OCF_RESKEY_PRE_STOP_USEREXIT_default}}
: ${OCF_RESKEY_POST_STOP_USEREXIT=${OCF_RESKEY_POST_STOP_USEREXIT_default}}

#######################################################################

SH=/bin/sh

usage() {
  methods=`sapdatabase_methods`
  methods=`echo $methods | tr ' ' '|'`
  cat <<-EOF
	usage: $0 ($methods)

	$0 manages a SAP database of any type as an HA resource.
        Currently Oracle, MaxDB, DB/2 UDB, Sybase ASE and SAP HANA Database are supported.
        ABAP databases as well as JAVA only databases are supported.

	The 'start' operation starts the instance.
	The 'stop' operation stops the instance.
	The 'status' operation reports whether the instance is running
	The 'monitor' operation reports whether the instance seems to be working
	The 'recover' operation tries to recover the instance after a crash (instance will be stopped first!)
	The 'validate-all' operation reports whether the parameters are valid
	The 'methods' operation reports on the methods $0 supports

	EOF
}

meta_data() {
	cat <<END
<?xml version="1.0"?>
<!DOCTYPE resource-agent SYSTEM "ra-api-1.dtd">
<resource-agent name="SAPDatabase">
<version>2.14</version>

<longdesc lang="en">
Resource script for SAP databases. It manages a SAP database of any type as an HA resource.

The purpose of the resource agent is to start, stop and monitor the database instance of a SAP system. Together with the RDBMS system it will also control the related network service for the database. Like the Oracle Listener and the xserver of MaxDB.
The resource agent expects a standard SAP installation of the database and therefore needs less parameters to configure.
The resource agent supports the following databases:
- Oracle 10.2, 11.2 and 12
- DB/2 UDB for Windows and Unix 9.x
- SAP-DB / MaxDB 7.x
- Sybase ASE 15.7
- SAP HANA Database since 1.00 - with SAP note 1625203 (http://sdn.sap.com)

In fact this resource agent does not run any database commands directly. It uses the SAP standard process SAPHostAgent to control the database.
The SAPHostAgent must be installed on each cluster node locally. It will not work, if you try to run the SAPHostAgent also as a HA resource.
Please follow SAP note 1031096 for the installation of SAPHostAgent.
The required minimum version of SAPHostAgent is:
Release: 7.20
Patch Number: 90
or compile time after: Dec 17 2011

To exemplify the usage, for a HANA database with SID "TST" and instance number "10", the resource configuration using crmsh syntax looks like:

primitive rsc_SAPDatabase_TST_HDB10 ocf:heartbeat:SAPDatabase \\
 params DBTYPE="HDB" SID="TST" \\
 op start interval="0" timeout="3600" \\
 op monitor interval="120" timeout="700" \\
 op stop interval="0" timeout="600"

Make sure to tune the operations timeout values accordingly with your chosen Database and available infrastructure.

Note that the same configuration can be achieved using any other CLI tool for cluster configuration available, like pcs or cibadmin. 
</longdesc>
<shortdesc lang="en">Manages a SAP database instance as an HA resource.</shortdesc>
<parameters>
 <parameter name="SID" unique="1" required="1">
  <longdesc lang="en">The unique database system identifier. e.g. P01</longdesc>
  <shortdesc lang="en">Database system ID</shortdesc>
  <content type="string" default="${OCF_RESKEY_SID_default}" />
 </parameter>
 <parameter name="DIR_EXECUTABLE" unique="0" required="0">
  <longdesc lang="en">The full qualified path where to find saphostexec and saphostctrl.
Usually you can leave this empty. Then the default: ${OCF_RESKEY_DIR_EXECUTABLE_default} is used.
  </longdesc>
  <shortdesc lang="en">path of saphostexec and saphostctrl</shortdesc>
  <content type="string" default="${OCF_RESKEY_DIR_EXECUTABLE_default}" />
 </parameter>
 <parameter name="DBTYPE" unique="0" required="1">
  <longdesc lang="en">The name of the database vendor you use. Set either: ADA, DB6, ORA, SYB, HDB</longdesc>
  <shortdesc lang="en">database vendor</shortdesc>
  <content type="string" default="${OCF_RESKEY_DBTYPE_default}" />
 </parameter>
 <parameter name="DBINSTANCE" unique="1" required="0">
  <longdesc lang="en">Must be used for special database implementations, when database instance name is not equal to the SID (e.g. Oracle DataGuard)</longdesc>
  <shortdesc lang="en">Database instance name, if not equal to SID</shortdesc>
  <content type="string" default="${OCF_RESKEY_DBINSTANCE_default}" />
 </parameter>
 <parameter name="DBOSUSER" unique="1" required="0">
  <longdesc lang="en">The parameter can be set, if the database processes on operating system level are not executed with the default user of the used database type. Defaults: ADA=taken from /etc/opt/sdb, DB6=db2SID, ORA=oraSID and oracle, SYB=sybSID, HDB=SIDadm</longdesc>
  <shortdesc lang="en">the Linux user that owns the database processes on operating system level</shortdesc>
  <content type="string" default="${OCF_RESKEY_DBOSUSER_default}" />
 </parameter>
 <parameter name="NETSERVICENAME" unique="0" required="0">
  <longdesc lang="en">Deprecated - do not use anymore. This parameter will be deleted in one of the next releases.</longdesc>
  <shortdesc lang="en">deprecated - do not use anymore</shortdesc>
  <content type="string" default="${OCF_RESKEY_NETSERVICENAME_default}" />
 </parameter>
 <parameter name="DBJ2EE_ONLY" unique="0" required="0">
  <longdesc lang="en">Deprecated - do not use anymore. This parameter will be deleted in one of the next releases.</longdesc>
  <shortdesc lang="en">deprecated - do not use anymore</shortdesc>
  <content type="boolean" default="${OCF_RESKEY_DBJ2EE_ONLY_default}"/>
 </parameter>
 <parameter name="JAVA_HOME" unique="0" required="0">
  <longdesc lang="en">Deprecated - do not use anymore. This parameter will be deleted in one of the next releases.</longdesc>
  <shortdesc lang="en">deprecated - do not use anymore</shortdesc>
  <content type="string" default="${OCF_RESKEY_JAVA_HOME_default}"/>
 </parameter>
 <parameter name="STRICT_MONITORING" unique="0" required="0">
  <longdesc lang="en">This controls how the resource agent monitors the database. If set to true, it will use 'saphostctrl -function GetDatabaseStatus' to test the database state. If set to false, only operating system processes are monitored.</longdesc>
  <shortdesc lang="en">Activates application level monitoring</shortdesc>
  <content type="boolean" default="${OCF_RESKEY_STRICT_MONITORING_default}"/>
 </parameter>
 <parameter name="AUTOMATIC_RECOVER" unique="0" required="0">
  <longdesc lang="en">If you set this to true, 'saphostctrl -function StartDatabase' will always be called with the '-force' option.</longdesc>
  <shortdesc lang="en">Enable or disable automatic startup recovery</shortdesc>
  <content type="boolean" default="${OCF_RESKEY_AUTOMATIC_RECOVER_default}"/>
 </parameter>
 <parameter name="MONITOR_SERVICES" unique="0" required="0">
  <longdesc lang="en">Defines which services are monitored by the SAPDatabase resource agent. Service names must correspond with the output of the 'saphostctrl -function GetDatabaseStatus' command.
The default MONITOR_SERVICES value is derived from the database type DBTYPE. For reference:

- DBTYPE "ORA" sets MONITOR_SERVICES="Instance|Database|Listener";
- DBTYPE "HDB" sets MONITOR_SERVICES="hdbindexserver|hdbnameserver";
- DBTYPE "ADA" sets MONITOR_SERVICES="Database";
- DBTYPE "DB6" sets MONITOR_SERVICES="{SID}|{db2sid}";
- DBTYPE "SYB" sets MONITOR_SERVICES="Server".

This parameter should be set ONLY if is needed to monitor different services than the ones listed above.
</longdesc>
  <shortdesc lang="en">Database services to monitor</shortdesc>
  <content type="string" default="${OCF_RESKEY_MONITOR_SERVICES_default}"/>
 </parameter>
 <parameter name="DIR_BOOTSTRAP" unique="0" required="0">
  <longdesc lang="en">Deprecated - do not use anymore. This parameter will be deleted in one of the next releases.</longdesc>
  <shortdesc lang="en">deprecated - do not use anymore</shortdesc>
  <content type="string" default="${OCF_RESKEY_DIR_BOOTSTRAP_default}" />
 </parameter>
 <parameter name="DIR_SECSTORE" unique="0" required="0">
  <longdesc lang="en">Deprecated - do not use anymore. This parameter will be deleted in one of the next releases.</longdesc>
  <shortdesc lang="en">deprecated - do not use anymore</shortdesc>
  <content type="string" default="${OCF_RESKEY_DIR_SECSTORE_default}" />
 </parameter>
 <parameter name="DB_JARS" unique="0" required="0">
  <longdesc lang="en">Deprecated - do not use anymore. This parameter will be deleted in one of the next releases.</longdesc>
  <shortdesc lang="en">deprecated - do not use anymore</shortdesc>
  <content type="string" default="${OCF_RESKEY_DB_JARS_default}" />
 </parameter>
 <parameter name="PRE_START_USEREXIT" unique="0" required="0">
  <longdesc lang="en">The full qualified path where to find a script or program which should be executed before this resource gets started.</longdesc>
  <shortdesc lang="en">path to a pre-start script</shortdesc>
  <content type="string" default="${OCF_RESKEY_PRE_START_USEREXIT_default}" />
 </parameter>
 <parameter name="POST_START_USEREXIT" unique="0" required="0">
  <longdesc lang="en">The full qualified path where to find a script or program which should be executed after this resource got started.</longdesc>
  <shortdesc lang="en">path to a post-start script</shortdesc>
  <content type="string" default="${OCF_RESKEY_POST_START_USEREXIT_default}" />
 </parameter>
 <parameter name="PRE_STOP_USEREXIT" unique="0" required="0">
  <longdesc lang="en">The full qualified path where to find a script or program which should be executed before this resource gets stopped.</longdesc>
  <shortdesc lang="en">path to a pre-start script</shortdesc>
  <content type="string" default="${OCF_RESKEY_PRE_STOP_USEREXIT_default}" />
 </parameter>
 <parameter name="POST_STOP_USEREXIT" unique="0" required="0">
  <longdesc lang="en">The full qualified path where to find a script or program which should be executed after this resource got stopped.</longdesc>
  <shortdesc lang="en">path to a post-start script</shortdesc>
  <content type="string" default="${OCF_RESKEY_POST_STOP_USEREXIT_default}" />
 </parameter>
</parameters>

<actions>
<action name="start" timeout="1800s" />
<action name="stop" timeout="1800s" />
<action name="status" timeout="60s" />
<action name="monitor" depth="0" timeout="60s" interval="120s" />
<action name="validate-all" timeout="5s" />
<action name="meta-data" timeout="5s" />
<action name="methods" timeout="5s" />
</actions>
</resource-agent>
END
}


#
# methods: What methods/operations do we support?
#
sapdatabase_methods() {
  cat <<-EOF
	start
	stop
	status
	monitor
	recover
	validate-all
	methods
	meta-data
	usage
	EOF
}


#
# sapuserexit : Many SAP customers need some additional processes/tools to run their SAP systems.
#               This specialties do not allow a totally generic SAP cluster resource agent.
#               Someone should write a resource agent for each additional process you need, if it
#               is required to monitor that process within the cluster manager. To enable
#               you to extent this resource agent without developing a new one, this user exit
#               was introduced.
#
sapuserexit() {
  NAME="$1"
  VALUE="$2"

  if [ -n "$VALUE" ]
  then
    if have_binary "$VALUE"
    then
      ocf_log info "Calling userexit ${NAME} with customer script file ${VALUE}"
      "$VALUE" >/dev/null 2>&1
      ocf_log info "Exiting userexit ${NAME} with customer script file ${VALUE}, returncode: $?"
    else
      ocf_log warn "Attribute ${NAME} is set to ${VALUE}, but this file is not executable"
    fi
  fi
  return $OCF_SUCCESS
}


#
# saphostctrl_installed
#
saphostctrl_installed() {
  SAPHOSTCTRL="${OCF_RESKEY_DIR_EXECUTABLE}/saphostctrl"
  SAPHOSTEXEC="${OCF_RESKEY_DIR_EXECUTABLE}/saphostexec"
  SAPHOSTSRV="${OCF_RESKEY_DIR_EXECUTABLE}/sapstartsrv"
  SAPHOSTOSCOL="${OCF_RESKEY_DIR_EXECUTABLE}/saposcol"

  have_binary $SAPHOSTCTRL && have_binary $SAPHOSTEXEC
}


#
#	'main' starts here...
#

if
  ( [ $# -ne 1 ] )
then
  usage
  exit $OCF_ERR_ARGS
fi

# These operations don't require OCF instance parameters to be set
case "$1" in
  meta-data)	meta_data
		exit $OCF_SUCCESS;;

  usage) 	usage
		exit $OCF_SUCCESS;;

  methods)	sapdatabase_methods
		exit $?;;

  *);;
esac

if  ! ocf_is_root
then
  ocf_log err "$0 must be run as root"
  exit $OCF_ERR_PERM
fi

# mandatory parameter check
if  [ -z "$OCF_RESKEY_SID" ]; then
  ocf_log err "Please set OCF_RESKEY_SID to the SAP system id!"
  exit $OCF_ERR_ARGS
fi
SID=`echo "$OCF_RESKEY_SID"`

if [ -z "$OCF_RESKEY_DBTYPE" ]; then
  ocf_log err "Please set OCF_RESKEY_DBTYPE to the database vendor specific tag (ADA,DB6,ORA,SYB,HDB)!"
  exit $OCF_ERR_ARGS
fi
DBTYPE=`echo "$OCF_RESKEY_DBTYPE" | tr '[:lower:]' '[:upper:]'`


# source functions and initialize global variables
if saphostctrl_installed; then
                    . ${OCF_FUNCTIONS_DIR}/sapdb.sh
else
                    if [ -n "${OCF_RESKEY_DBOSUSER}" ]; then
                      ocf_exit_reason "Usage of parameter OCF_RESKEY_DBOSUSER is not possible without having SAP Host-Agent installed"
                      exit $OCF_ERR_ARGS
                    fi
                    . ${OCF_FUNCTIONS_DIR}/sapdb-nosha.sh
fi
sapdatabase_init


# we always want to fall to the faster status method in case of a probe by the cluster
ACTION=$1
if ocf_is_probe
then
  ACTION=status
fi

# What kind of method was invoked?
case "$ACTION" in

  start|stop|status|recover)   sapdatabase_$ACTION
                               exit $?;;
  monitor)                     sapdatabase_monitor $OCF_RESKEY_STRICT_MONITORING
                               exit $?;;
  validate-all)                sapdatabase_validate
                               exit $?;;
  *)		                   sapdatabase_methods
                               exit $OCF_ERR_UNIMPLEMENTED;;
esac
